import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 引入接口函数
import { seller, list } from "../api/sellapp"
export default new Vuex.Store({
  state: {
    shopdata: {},//店铺数据
    goodsdata: [],//商品列表数据
    color:"#999999"//购物车颜色
  },

  mutations: {
    SET_SHOP_DATA(state, shopdata) {
      state.shopdata = shopdata
    },

    SET_GOODS_DATA(state, goodsdata) {
      state.goodsdata = goodsdata
    },

    SET_SHOP_CAR(state, color) {
      state.color = color
    },
  },

  actions: {
    // 获取店铺信息
    get_shop_data({ commit }) {
      return new Promise(async (resolve, reject) => {
        let res = await seller();
        let { data } = res.data
        commit("SET_SHOP_DATA", data)
        resolve(data)
      })
    },

    //获取商品列表信息
    get_goods_data({ commit }) {
      return new Promise(async (resolve, reject) => {
        let res = await list()
        let { goodsList } = res.data
        goodsList.forEach((v: any) => {
          v.foods.forEach((subV: any) => {
            subV.count = 0
          })
        })
        commit("SET_GOODS_DATA", goodsList)
        resolve(goodsList)
      })
    },

    //更改购物车颜色
    get_shop_car({commit}){
      commit("SET_SHOP_CAR","#ffc300")
    },
    get_shop_car2({commit}){
      commit("SET_SHOP_CAR","#999999")
    }
  },

  getters: {//选中的商品数据
    selectedData(state) {
      const selectedDataArray: any = []
      state.goodsdata.forEach((v: any) => {
        v.foods.forEach((subV: any) => {
          if (subV.count && subV.count > 0) {
            selectedDataArray.push(subV)
          }
        })
      })
      return selectedDataArray
    },

    totalcount(state, { selectedData }) {//总数量
      let totallist: any = []
      selectedData.forEach((v: any) => {
        totallist.push(v.count)
      })
      let totalcount = 0
      totalcount = totallist.reduce((total: any, cur: any) => {
        return total + cur
      }, 0)
      return totalcount
    },

    totalprice(state, { selectedData }) {//总价格
      let totalprice = 0
      selectedData.forEach((v: any) => {
        totalprice += v.count * v.price
      })
      return totalprice.toFixed(2)
    },

    psfprice(state, { totalprice }) {// 配送费
      return (50 - totalprice > 0 ? 50 - totalprice : 0).toFixed(2)
    }
  },

  modules: {
  }
})
